package com.zelin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zelin.mapper.ClassesMapper;
import com.zelin.mapper.StudentMapper;
import com.zelin.pojo.Classes;
import com.zelin.pojo.Student;
import com.zelin.pojo.StudentExample;
import com.zelin.service.StudentService;
import com.zelin.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
//    @Autowired
//    private StudentMapper studentMapper;
//
//    @Autowired
//    private ClassesMapper classesMapper;
//
//    @Override
//    public List<Student> getAllStudents() {
//        List<Student> students = studentMapper.selectAll();
//        for (Student stu : students){
//            Classes classes = classesMapper.selectByPrimaryKey(stu.getCid());
//            stu.setCname(classes.getCname());
//        }
//        return students;
//    }


    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;
    @Override
    public List<Student> findAll() {
        //1.查询出所有学生
        List<Student> students = studentMapper.selectAll();
        //2.遍历学生,为学生的cname字段赋值
        for (Student student : students) {
            student.setCname(classesMapper.selectByPrimaryKey(student.getCid()).getCname());
        }
        return students;
    }

    /**
     *
     * @param page
     * @param pagesize
     * @param student
     * @return
     */
    @Override
    public PageResult<Student> search(int page, int pagesize, Student student) {
        //1.开始分页
        PageHelper.startPage(page,pagesize);
        //2.条件查询
        //2.1)构造查询实例
        StudentExample example = new StudentExample();
        //2.2)添加查询条件
        StudentExample.Criteria criteria = example.createCriteria();
        if(student != null){
            if(!StringUtils.isEmpty(student.getSname())){
                criteria.andSnameLike("%" + student.getSname() + "%");
            }
            if(!StringUtils.isEmpty(student.getAddr())){
                criteria.andAddrLike("%" + student.getAddr() + "%");
            }
            if(!StringUtils.isEmpty(student.getCid())){
                criteria.andCidEqualTo(student.getCid());
            }
        }
        //3.得到分页查询对象
        List<Student> students = studentMapper.selectByExample(example);
        //3.1)添加班级名称
        for (Student st : students) {
            Classes classes = classesMapper.selectByPrimaryKey(st.getCid());
            st.setCname(classes.getCname());
        }
        //3.2)将上面有班级信息的学生集合转换为分页结果对象
        Page<Student> studentPage = (Page<Student>) students;
        //4.构造PageResult结果对象并返回
        return new PageResult<>(studentPage.getResult(),studentPage.getTotal());
    }
}
